package com.verisette.ncos.service.master.bizunit;

import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Required;

import org.corp.agi.common.constant.CommonConstant;
import org.corp.agi.common.exception.BusinessException;
import org.corp.agi.common.exception.ProcessException;
import org.corp.agi.common.exception.TechnicalException;
import org.corp.agi.service.bean.ProcessContext;
import org.corp.agi.service.bean.UserBean;
import org.corp.agi.service.bizunit.CommonBusinessUnit;
import org.corp.common.util.security.Encrypter;
import com.verisette.ncos.common.ProjectConstant;
import com.verisette.ncos.persistence.domain.MasterUserGroupToUserProfile;
import com.verisette.ncos.persistence.domain.MasterUserProfile;

public class CreateUserProfileManagementBU extends CommonBusinessUnit {

	private Logger logger = Logger.getLogger(CreateUserProfileManagementBU.class);
	
	private Encrypter encrypter;
	@Autowired
	@Required
	public void setEncrypter(@Qualifier("encrypter")Encrypter encrypter) {
		this.encrypter = encrypter;
	}
	
	@Override
	public void execute(ProcessContext processContext) throws ProcessException {
		if(logger.isInfoEnabled()) logger.info( this.getClass().getSimpleName() + ": execute" );
		
		Map<String, Object> inputMap = (Map<String, Object>)processContext.getValueObject();
		MasterUserProfile userProfile = (MasterUserProfile)inputMap.get(ProjectConstant.USER_PROFILE);
		String[] assignedRoles = (String[])inputMap.get(ProjectConstant.USER_PROFILE_ASSIGNED_ROLE);
		
		UserBean user = processContext.getUserBean();
		Date currentDate = new Date();
		
		try {

			// Check same userName
			logger.debug("1.Check same userName.");
			MasterUserProfile criteriaUser = new MasterUserProfile();
			criteriaUser.setUspUserName(userProfile.getUspUserName());
			List<MasterUserProfile> foundList = (List<MasterUserProfile>)commonDAO.findByExample(criteriaUser);
			
			if(foundList.size() != 0){
				// Same userName
				throw new BusinessException(ProjectConstant.MESSAGE_CODE_USP0002);
				
			}
			
			// Insert UserProfile into MASTER_USER_PROFILE
			logger.debug("1.Insert UserProfile into MASTER_USER_PROFILE.");

			//userProfile.setUspPassword(encrypter.encrypt(userProfile.getUspPassword())); comment by pimonrath 29/10/2010 because fix default password
			userProfile.setUspPassword(encrypter.encrypt(ProjectConstant.DEFAULT_PASSWORD));
			userProfile.setUspCreatedDate(new Timestamp(currentDate.getTime()));
			userProfile.setUspCreatedBy(user.getUsername());
			//userProfile.setUspLastUpdatedDate(new Timestamp(currentDate.getTime()));
			//userProfile.setUspLastUpdatedBy(user.getUsername());
			
			// Add by thippawan @2010-09-22
			// calculate expire date for add
			/* comment by pimonrath 09/11/2010 create user not insert field expireDate
			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.DAY_OF_MONTH, Integer.parseInt(ProjectConstant.EXPIRE_DAY));
			userProfile.setUspExpireDate(new Timestamp(cal.getTimeInMillis()));
			*/
			
			// set default value from Spec.
			userProfile.setUspWrongLoginCounter(new Short("0"));
			userProfile.setUspLockFlag(ProjectConstant.N_FLAG);
			userProfile.setUspForceChngPwdFlag(ProjectConstant.Y_FLAG);
			
			commonDAO.save(userProfile);
			commonDAO.flush();

			logger.debug("--> uspId : " + userProfile.getUspId());

			// Insert groupRole into MASTER_USER_USG_TO_USG
			logger.debug("2.Insert group role  into MASTER_USER_USG_TO_USP.");


			MasterUserGroupToUserProfile usgToUsp = null;
			for(String groupId : assignedRoles){
				logger.debug("--> roleId : " + groupId);
				usgToUsp = new MasterUserGroupToUserProfile();

				usgToUsp.setUsgId(Integer.parseInt(groupId));
				usgToUsp.setUspId(userProfile.getUspId());
				usgToUsp.setUgpStatus(ProjectConstant.ACTIVE_FLAG);
				usgToUsp.setUgpCreatedDate(new Timestamp(currentDate.getTime()));
				usgToUsp.setUgpCreatedBy(user.getUsername());
				//usgToUsp.setUgpLastUpdatedDate(new Timestamp(currentDate.getTime()));
				//usgToUsp.setUgpLastUpdatedBy(user.getUsername());
				commonDAO.save(usgToUsp);

			}

		} catch (NumberFormatException e) {
			logger.debug("--> Error convert Number !!!");
			throw new TechnicalException( CommonConstant.MESSAGE_CODE_AGI0001, e);

		} catch (NoSuchAlgorithmException e1) {
			e1.printStackTrace();
		}

	}

}
